<?php
class SearchUtility {

	private function __construct() {}
	
	/**
	 * Get Search result by cityId
	 * @param $clauses, $selectedSearchId, $pageNumber, $quantity
	 * @return array
	*/
	public static function getSearchForHome( $clauses=array(), $selectedSearchId=0, $pageNumber=1, $quantity=50 ){
		try{
			$locations = array();
			$whereClause = array( 'usageId||>0', 'googleLocationId||>0', 'status||active', 'paging||Y', "pageNumber||$pageNumber", "quantity||$quantity" );
			if( isset( $clauses[ 'usageId' ] ) ){
				$usageId = $clauses[ 'usageId' ];
				if( is_numeric( $usageId ) && $usageId > 0 ){
					if( isset( $clauses[ 'usageType' ] ) ){
						$usageType = $clauses[ 'usageType' ];
						if( $usageType != '' ){
							$whereClause[] = "usageType||$usageType";
							$whereClause[] = "usageId||$usageId";
						}
					}
				}
			}
			if( isset( $clauses[ 'cityId' ] ) ){
				$cityId = $clauses[ 'cityId' ];
				if( is_numeric( $cityId ) && $cityId > 0 ){
					$whereClause[] = "cityId||$cityId";
				}
			}
			if( isset( $clauses[ 'stateId' ] ) ){
				$stateId = $clauses[ 'stateId' ];
				if( is_numeric( $stateId ) && $stateId > 0 ){
					$whereClause[] = "stateId||$stateId";
				}
			}
			if( isset( $clauses[ 'countryId' ] ) ){
				$countryId = $clauses[ 'countryId' ];
				if( is_numeric( $countryId ) && $countryId > 0 ){
					$whereClause[] = "countryId||$countryId";
				}
			}

			if( isset( $clauses[ 'categoryId' ] ) ){
				$categoryId = $clauses[ 'categoryId' ];
				if( is_numeric( $categoryId ) && $categoryId > 0 ){
					if( isset( $clauses[ 'categoryLevel' ] ) ){
						$categoryLevel = $clauses[ 'categoryLevel' ];
						if( $categoryLevel != '' ){
							$whereClause[] = "categoryLevel||$categoryLevel";
							$whereClause[] = "categoryId||$categoryId";
						}
					}else{
						$whereClause[] = "categoryId||0";
						$whereClause[] = "categoryLevel||none";
					}
				}else{
					$whereClause[] = "categoryId||0";
					$whereClause[] = "categoryLevel||none";
				}
			}else{
				$whereClause[] = "categoryId||0";
				$whereClause[] = "categoryLevel||none";
			}

			$isAjaxCall = isset( $clauses[ 'ajaxcall' ] ) ? true : false;
			$indx = 1;
			$objSearch = getMultiple( 'search', $whereClause );
			//describe( $whereClause, $objSearch->getResultCount(), true );
			foreach( $objSearch() as $i => $searchObj ){
				$searchId = $searchObj->getSearchId();
				$googleLocationId = $searchObj->getGoogleLocationId();
				$objLocation = getSingle( 'googleLocation', $googleLocationId );
				if( $objLocation->getResultCount() <= 0 ){
					continue;
				}

				$element = array();
				if( !$isAjaxCall ){
					// get searched element details
					$element = self::getSearchedElementDetail( $searchObj->getUsageId(), $searchObj->getUsageType()  );
					if( count( $element ) <= 0 ){
						return false;
					}
				}

				$address = $objLocation->getFormattedAddress();
				$shortAddress = strlen( $address ) > 15 ? substr( $address, 0, 12 ) . '...' : $address;

				$title = $objLocation->getGName();
				$title = $title != '' ? $title : $address;

				$latitude = $objLocation->getLatitude();
				$latitude1 = round( $latitude, 2 );

				$longitude = $objLocation->getLongitude();
				$longitude1 = round( $longitude, 2 );

				$indx = $selectedSearchId > 0 ? $indx : $i;
				if( $selectedSearchId == $searchId ){
					$locations[ 0 ] = array( 'indx' =>  $searchObj->getSearchId(), 'id' => $objLocation->getGoogleLocationId(), 'title' => $title,
						'latitude' => $latitude, 'longitude' => $longitude, 'latitude1' => "$latitude1", 'longitude1' => "$longitude1",
						'address' => $address, 'shortAddress' => $shortAddress, 'city' => $objLocation->getCity(),
						'state' => $objLocation->getState(), 'country' => $objLocation->getCountry(), 
						'countryCode' => $objLocation->getCountryCode(), 'element' => $element
					);
				}else{
					$locations[ $indx ] = array( 'indx' => $searchObj->getSearchId(), 'id' => $objLocation->getGoogleLocationId(), 'title' => $title,
						'latitude' => $latitude, 'longitude' => $longitude, 'latitude1' => "$latitude1", 'longitude1' => "$longitude1",
						'address' => $address, 'shortAddress' => $shortAddress, 'city' => $objLocation->getCity(),
						'state' => $objLocation->getState(), 'country' => $objLocation->getCountry(), 
						'countryCode' => $objLocation->getCountryCode(), 'element' => $element
					);
				}
				$indx++;
			}
			ksort( $locations );
			return array_values( $locations );
		}catch( Exception $ex ){
			throw $ex;
		}
	}

	/**
	 * Get Search element details
	 * @param $usageId, $usageType
	 * @return array
	*/
	public static function getSearchedElementDetail( $usageId, $usageType ){
		try{
			$element = array();
			if( !is_numeric( $usageId ) || $usageId <= 0 || $usageType == '' ){
				return $element;
			}
			switch( $usageType ) {
				case 'company' : {
					try{
						$objCompany = getMultiple( 'company', "companyId||$usageId" );
						if( $objCompany->getResultCount() > 0 ){
							$imagePath = $objCompany->getImagePath();
							$imagePath = $imagePath != '' ? ImageUtility::getScaledImage( $imagePath, 97, 68 ):'/images/search/img97X68.jpg';

							$coverImagePath = $objCompany->getCoverImagePath();
							$coverImagePath = $coverImagePath != ''? ImageUtility::getScaledImage( $coverImagePath, 300, 213 ):'/images/search/img300X213.jpg';
							
							$likesCount = Conversation::getLikesCount( 'company', $usageId );
							$reviewsCount = CompanyUtility::getCompanyReviewsCount( $usageId );

							$link = $objCompany->getSlug() != '' ? "http://" . $objCompany->getSlug() . '.' . HOST_NAME : 'javascript:;';
							$element = array(
								'title' => $objCompany->getName(), 'imagePath' => $imagePath, 'coverImagePath' => $coverImagePath,
								'about' => $objCompany->getAbout(), 'rating' => $objCompany->getRating(), 'rating1' => rand( 0, 9 ), 
								'pageViews' => $objCompany->getPageViews(), 'likes' => $likesCount, 'reviews' => $reviewsCount,
								'link' => $link, 'id' => $usageId, 'type' => 'company'
							);
						}
					}catch( Exception $ex ){}
					break;
				}case 'tour' : {
					try{
						$objTour = getMultiple( 'tour', "tourId||$usageId", 'tourType||public' );
						if( $objTour->getResultCount() > 0 ){
							$objTourData = getMultiple( 'tourData', "tourId||$usageId" );
							if( $objTourData->getResultCount() > 0 ){
								$imagePath = $objTourData->getImagePath();
								$imagePath = $imagePath != '' ? ImageUtility::getScaledImage( $imagePath, 97, 68 ):'/images/search/img97X68.jpg';

								$coverImagePath = $objTourData->getCoverImagePath();
								$coverImagePath = $coverImagePath != ''? ImageUtility::getScaledImage( $coverImagePath, 300, 213 ):'/images/search/img300X213.jpg';
								
								$likesCount = Conversation::getLikesCount('tour', $usageId);
								$reviewsCount = 0;

								$link = $objTour->getSlug() != '' ? "http://" . $objTour->getSlug() . '.' . HOST_NAME : 'javascript:;';
								$element = array(
									'title' => $objTour->getName(), 'imagePath' => $imagePath, 'coverImagePath' => $coverImagePath,
									'about' => $objTourData->getDescription(), 'rating' => $objTour->getRating(), 
									'pageViews' => $objTour->getPageViews(), 'likes' => $likesCount, 'reviews' => $reviewsCount, 
									'id' => $usageId, 'type' => 'tour', 'link' => $link
								);
							}
						}
					}catch( Exception $ex ){}
					break;
				}case 'event' : {
					try{
						$objEvent = getMultiple( 'event', "eventId||$usageId", 'eventType||public' );
						if( $objEvent->getResultCount() > 0 ){
							$objEventEdition = getMultiple( 'eventEdition', "eventId||$usageId" );
							if( $objEventEdition->getResultCount() > 0 ){
								$imagePath = $objEventEdition->getImagePath();
								$imagePath = $imagePath != '' ? ImageUtility::getScaledImage( $imagePath, 97, 68 ):'/images/search/img97X68.jpg';

								$coverImagePath = $objEventEdition->getCoverImagePath();
								$coverImagePath = $coverImagePath != ''? ImageUtility::getScaledImage( $coverImagePath, 300, 213 ):'/images/search/img300X213.jpg';
								
								$likesCount = Conversation::getLikesCount('event', $usageId);
								$reviewsCount = 0;

								$link = $objTour->getSlug() != '' ? "http://" . $objTour->getSlug() . '.' . HOST_NAME : 'javascript:;';

								$element = array(
									'title' => $objEvent->getName(), 'imagePath' => $imagePath, 'coverImagePath' => $coverImagePath,
									'about' => $objEventEdition->getAbout(), 'rating' => $objEvent->getRating(), 
									'pageViews' => $objEvent->getPageViews(), 'likes' => $likesCount, 'reviews' => $reviewsCount, 
									'id' => $usageId, 'type' => 'event', 'link' => $link
								);
							}
						}
					}catch( Exception $ex ){}
					break;
				}
			}
			return $element;
		}catch( Exception $ex ){
			throw $ex;
		}
	}

	/**
	 * Process Company by there offices locations to search table 
	 * @param $companyId
	*/
	public static function processCompanyToSearchByOfficeLocations( $companyId ){
		try{
			if( !is_numeric( $companyId ) || $companyId <= 0 ){
				return false;
			}
			// remove all the company's data from search table
			self::removeAllSearchDataByUsageType( $companyId, 'company' );
			// get all company offices locations
			$objOffices = getMultiple( 'companyOffice', "companyId||$companyId", 'googleLocationId||>0', 'quantity||1000' );
			foreach( $objOffices() as $objOffice ){
				$googleLocationId = $objOffice->getGoogleLocationId();
				$objLocation = getSingle( 'googleLocation', $googleLocationId );
				if( $objLocation->getResultCount() > 0 ){
					// add data to search table
					$cityId = $objLocation->getCityId();
					$stateId = $objLocation->getStateId();
					$countryId = $objLocation->getCountryId();
					if( $cityId <= 0 || $stateId <= 0 || $countryId <= 0 ){
						continue;
					}
					// add data to search table
					$postVars = array( 
						'usageId' => $companyId, 'usageType' => 'company', 'cityId' => $cityId, 
						'stateId' => $stateId, 'countryId' => $countryId, 'googleLocationId' => $googleLocationId 
					);
					self::addSearchData( $postVars );
					// add company's business interest categories to search table
					self::processCompanyBICategoriesToSearch( $companyId, $googleLocationId, $cityId, $stateId, $countryId );
				}
			}
		}catch( Exception $ex ){
			throw $ex;
		}
	}

	/**
	 * Add company business iterest categories to search table;
	 * @param $postVars
	*/
	public static function processCompanyBICategoriesToSearch( $companyId, $googleLocationId, $cityId, $stateId, $countryId ){
		try{
			if( !is_numeric( $companyId ) || $companyId <= 0 ){
				return false;
			}
			if( !is_numeric( $googleLocationId ) || $googleLocationId <= 0 ){
				return false;
			}
			if( !is_numeric( $cityId ) || $cityId <= 0 ){
				return false;
			}
			if( !is_numeric( $stateId ) || $stateId <= 0 ){
				return false;
			}
			if( !is_numeric( $countryId ) || $countryId <= 0 ){
				return false;
			}
			// Get all company's business interest and add them to search table
			$objCompanyBIs = getMultiple( 'companyBusinessInterest', "companyId||$companyId", 
				'sortColumn||priority', 'sortOrder||asc', 'quantity||1000' );
			foreach( $objCompanyBIs() as $objCompanyBI ){
				$postVars = array( 'usageId' => $companyId, 'usageType' => 'company', 'googleLocationId' => $googleLocationId, 
					'cityId' => $cityId, 'stateId' => $stateId, 'countryId' => $countryId, 
					'categoryId' => $objCompanyBI->getBusinessInterestId(), 'categoryLevel' => 'one' );
				// add data to search table
				self::addSearchData( $postVars );
			}
			if( $objCompanyBIs->getResultCount() > 0 ){
				// Get all company's business interest's categories and add them to search table
				$objCompanyBICats = getMultiple( 'companyBusinessInterestCategory', "companyId||$companyId", 
					'sortColumn||priority', 'sortOrder||asc', 'quantity||1000' );
				foreach( $objCompanyBICats() as $objCompanyBICat ){
					$postVars = array( 'usageId' => $companyId, 'usageType' => 'company', 'googleLocationId' => $googleLocationId, 
						'cityId' => $cityId, 'stateId' => $stateId, 'countryId' => $countryId,
						'categoryId' => $objCompanyBICat->getBusinessInterestCategoryId(), 'categoryLevel' => 'two' );
					// add data to search table
					self::addSearchData( $postVars );
				}
			}
		}catch( Exception $ex ){
			throw $ex;
		}
	}


	/**
	 * Add Search data from search table 
	 * @param $postVars
	 * @return searchId
	*/
	public static function addSearchData( $postVars ){
		try{
			$usageId = isset( $postVars[ 'usageId' ] ) ? $postVars[ 'usageId' ] : 0;
			if( !is_numeric( $usageId ) || $usageId <= 0 ){
				return false;
			}
			$usageType = isset( $postVars[ 'usageType' ] ) ? $postVars[ 'usageType' ] : '';
			if( $usageType == '' ){
				return false;
			}
			$googleLocationId = isset( $postVars[ 'googleLocationId' ] ) ? $postVars[ 'googleLocationId' ] : 0;
			if( !is_numeric( $googleLocationId ) || $googleLocationId <= 0 ){
				return false;
			}
			$cityId = isset( $postVars[ 'cityId' ] ) ? $postVars[ 'cityId' ] : 0;
			if( !is_numeric( $cityId ) || $cityId <= 0 ){
				return false;
			}
			$stateId = isset( $postVars[ 'stateId' ] ) ? $postVars[ 'stateId' ] : 0;
			if( !is_numeric( $stateId ) || $stateId <= 0 ){
				return false;
			}
			$countryId = isset( $postVars[ 'countryId' ] ) ? $postVars[ 'countryId' ] : 0;
			if( !is_numeric( $countryId ) || $countryId <= 0 ){
				return false;
			}
			$categoryId = isset( $postVars[ 'categoryId' ] ) ? $postVars[ 'categoryId' ] : 0;
			$categoryLevel = isset( $postVars[ 'categoryLevel' ] ) ? $postVars[ 'categoryLevel' ] : 'none';
			$rating = isset( $postVars[ 'rating' ] ) ? $postVars[ 'rating' ] : 0;

			$canAddSearch = false;
			if( $categoryId > 0 ){
				$searchCatChkObj = getMultiple( 'search', 'count||Y', "usageId||$usageId", "usageType||$usageType", 
					"googleLocationId||$googleLocationId", "categoryId||$categoryId", "categoryLevel||$categoryLevel" );
				if( $searchCatChkObj->getTotalCount() == 0 ){
					$canAddSearch = true;
				}
			}else{
				$searchChkObj = getMultiple( 'search', "usageId||$usageId", 
					"usageType||$usageType", "googleLocationId||$googleLocationId", 'count||Y' );
				if( $searchChkObj->getTotalCount() == 0 ){
					$canAddSearch = true;
				}
			}

			$searchId = 0;
			if( $canAddSearch ){
				// add search data
				$searchId = getDb( 'search', 'add' )->set( "usageId||$usageId", "usageType||$usageType", 
					"categoryId||$categoryId", "categoryLevel||$categoryLevel", "rating||$rating", 
					"cityId||$cityId", "stateId||$stateId", "countryId||$countryId", 
					"googleLocationId||$googleLocationId" )->getLastInsertedId(); 
			}
			return $searchId;
		}catch( Exception $ex ){
			throw $ex;
		}
	}

	/**
	 * Remove data from search table by usageType
	 * @param $usageId, $usageType
	 * @return true/false
	*/
	public static function removeAllSearchDataByUsageType( $usageId, $usageType ){
		try{
			if( !is_numeric( $usageId ) || $usageId <= 0 ){
				return false;
			}
			if( $usageType == '' ){
				return false;
			}
			// check and remove all the company entries from search table
			if( getMultiple( 'search', "usageId||$usageId", "usageType||$usageType", 'count||Y' )->getTotalCount() > 0 ){
				getDb( 'search', 'delete' )->set( "whereClause||usageId = $usageId and usageType = '$usageType'" );
				return true;
			}
			return false;
		}catch( Exception $ex ){
			throw $ex;
		}
	}
	
}